package cn.edu.sjtu.se.peakfactory.service.impls;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.edu.sjtu.se.peakfactory.dao.bean.Coupon;
import cn.edu.sjtu.se.peakfactory.dao.bean.UserCoupon;
import cn.edu.sjtu.se.peakfactory.dao.interfaces.CouponDAO;
import cn.edu.sjtu.se.peakfactory.dao.interfaces.UserCouponDAO;
import cn.edu.sjtu.se.peakfactory.service.bean.CouponVB;
import cn.edu.sjtu.se.peakfactory.service.bean.UserCouponVB;
import cn.edu.sjtu.se.peakfactory.service.interfaces.CouponService;

public class CouponServiceImpl implements CouponService {
	private CouponDAO couponDAO;
	private UserCouponDAO userCouponDAO;

	public void setCouponDAO(CouponDAO couponDAO) {
		this.couponDAO = couponDAO;
	}

	public void setUserCouponDAO(UserCouponDAO userCouponDAO) {
		this.userCouponDAO = userCouponDAO;
	}

	@Override
	public List<CouponVB> searchCouponByName(String couponName) {
		List<Coupon> coupons = couponDAO.searchCouponByName(couponName);
		List<CouponVB> result = new ArrayList<CouponVB>();
		for (Coupon c : coupons) {
			result.add(new CouponVB(c));
		}
		return result;
	}

	@Override
	public List<CouponVB> getAllCoupons() {
		List<Coupon> coupons = couponDAO.findByHql("from Coupon", null);
		List<CouponVB> result = new ArrayList<CouponVB>();
		for (Coupon c : coupons) {
			result.add(new CouponVB(c));
		}
		return result;
	}

	@Override
	public List<UserCouponVB> getUserCoupons(Long userId) {
		List<UserCoupon> coupons = userCouponDAO.getUserCoupons(userId);
		List<UserCouponVB> result = new ArrayList<UserCouponVB>();
		for (UserCoupon c : coupons) {
			result.add(new UserCouponVB(c));
		}
		return result;
	}

	@Override
	public UserCouponVB getUserCouponsById(Long userId, Long couponId) {
		UserCoupon userCoupon = userCouponDAO.getUserCouponsById(userId, couponId);
		return new UserCouponVB(userCoupon);
	}

	@Override
	public void gainUserCoupon(Long userId, Long couponId) {
		userCouponDAO.gainUserCoupon(userId, couponId, new Date());
	}

	@Override
	public void useUserCoupon(Long userId, Long couponId) {
		userCouponDAO.useUserCoupon(userId, couponId, new Date());
	}
}
